/*
 * @Description: 页面守卫配置
 * @Author: qingyang
 * @Date: 2023-01-12 14:42:48
 * @LastEditors: qingyang
 * @LastEditTime: 2023-05-22 10:39:56
 */
import type { Router } from 'vue-router';
import { ElNotification, ElButton } from 'element-plus';
import { h } from 'vue';
import NProgress from 'nprogress';

NProgress.configure({ showSpinner: false });
export const createPageGuard = (router: Router) => {
  router.beforeEach(async () => {
    NProgress.start();
    return true;
  });
  router.afterEach((to, from) => {
    // 关闭进度条
    NProgress.done();
  });
  router.onError((error: Error) => {
    const pattern = /Loading chunk (\S)+ failed/g;
    const isChunkLoadFailed = error.message.match(pattern);
    if (isChunkLoadFailed) {
      ElNotification({
        title: '页面已更新',
        message: h('div', { style: 'color: teal' }, [
          '请刷新页面使用最新版页面',
          h(
            ElButton,
            {
              style: 'margin-left: 10px',
              onClick: () => {
                window.location.reload();
              }
            },
            '刷新'
          )
        ]),
        position: 'bottom-left',
        duration: 0
      });
    }
  });
};
